package com.xiyou.week05.binarySearch;

/**
 * 1011. 在 D 天内送达包裹的能力
 *
 * @ClassName：ShipWithinDays
 * @Author：西柚
 * @Date：2022/1/28 2:08 下午
 * @Versiion：1.0
 */
public class ShipWithinDays {

    /**
     * 输入：weights = [1,2,3,4,5,6,7,8,9,10], days = 5
     * 输出：15
     * 解释：
     * 船舶最低载重 15 就能够在 5 天内送达所有包裹，如下所示：
     * 第 1 天：1, 2, 3, 4, 5
     * 第 2 天：6, 7
     * 第 3 天：8
     * 第 4 天：9
     * 第 5 天：10
     * <p>
     * 请注意，货物必须按照给定的顺序装运，因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
     * <p>
     * 链接：https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days
     *
     * @param weights
     * @param days
     * @return
     */
    public int shipWithinDays(int[] weights, int days) {
        int left = 0, right = 0;
        for (int num : weights) {
            left = Math.max(left, num);
            right += num;
        }
        while (left < right) {
            int mid = (left + right) / 2;
            if (validate(weights, days, mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return right;
    }

    private boolean validate(int[] weights, int m, int now) {
        int box = 0;
        int count = 1;
        for (int num : weights) {
            if (box + num <= now) {
                box += num;
            } else {
                count++;
                box = num;
            }
        }
        return count <= m;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 3, 1, 1};
        int days = 4;
        ShipWithinDays shipWithinDays = new ShipWithinDays();
        System.out.println(shipWithinDays.shipWithinDays(nums, days));
    }

}
